package com.le.tester.compared;

import java.util.concurrent.atomic.AtomicLong;

/**
 * createTime：2021/11/18 9:42
 * description：volatile结合AtomicLong，保证原子性，性能优化，请看LongAdderTest
 */
public class AtomicLongTest {
    private static final int THREAD_COUNT = 20;

    private static volatile AtomicLong race = new AtomicLong(0);

    public static void increment() {
        race.getAndIncrement();
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[THREAD_COUNT];

        for (int i = 0; i < THREAD_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    increment();
                }
            });
            threads[i].start();
        }

        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println("race is " + race);
    }
}
